package com.common.groovy.action;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.common.groovy.model.ActionModel;
import com.common.groovy.model.DataModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public interface IAction<P, R> {

    R execute(ActionModel actionDetail, DataModel data, P params);


    /**
     * 解析sql语句，并执行sql脚本
     *
     * @param sql
     * @param result
     * @return
     */
    default R executeSql(String sql, JSONObject result) {
        String parseSqlContent = parseSql(sql, result);
        parseSqlContent = parseSqlContent.replaceAll("'null'", "null");
        parseSqlContent = parseSqlContent.replaceAll("''", "null");
        return processSql(parseSqlContent);
    }

    default String parseSql(String sql, JSONObject result) {
        //将result转换为Map作为变量上下文
        Map<String, Object> context = new HashMap<>();
        if (result != null) {
            context = result;
        }

        //处理[[]]
        Pattern conditionPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.DOTALL);
        Matcher conditionMatcher = conditionPattern.matcher(sql);
        StringBuffer parsedSql = new StringBuffer();
        while (conditionMatcher.find()) {
            String innerContent = conditionMatcher.group(1);
            // 检查内部是否有变量标签{{...}}
            Pattern varPattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
            Matcher varMatcher = varPattern.matcher(innerContent);

            if (!varMatcher.find()) {
                // 没有变量标签：移除条件标签，保留内容
                conditionMatcher.appendReplacement(parsedSql, Matcher.quoteReplacement(innerContent));
            } else {
                // 有变量标签：检查所有变量是否非空
                boolean allVarsValid = true;
                List<String> varNames = new ArrayList<>();
                varMatcher.reset(); // 重置匹配器
                while (varMatcher.find()) {
                    String varName = varMatcher.group(1).trim();
                    varNames.add(varName);
                    if (!context.containsKey(varName)) {
                        allVarsValid = false;
                        break;
                    }
//                    Object value = context.get(varName);
//                    if (value == null || (value instanceof String && ((String) value).isEmpty())) {
//                        allVarsValid = false;
//                        break;
//                    }
                }

                if (allVarsValid) {
                    // 变量有效：替换变量并保留内容
                    String replacedContent = innerContent;
                    for (String varName : varNames) {
                        Object value = context.get(varName);
                        replacedContent = replacedContent.replaceAll(
                                "\\{\\{" + Pattern.quote(varName) + "\\}\\}",
                                Matcher.quoteReplacement(String.valueOf(value))
                        );
                    }
                    conditionMatcher.appendReplacement(parsedSql, Matcher.quoteReplacement(replacedContent));
                } else {
                    // 变量无效：移除整个条件块
                    conditionMatcher.appendReplacement(parsedSql, "");
                }
            }
        }
        conditionMatcher.appendTail(parsedSql);
        sql = parsedSql.toString();

        //处理剩余变量标签{{...}}
        Pattern varPattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
        Matcher varMatcher = varPattern.matcher(sql);
        parsedSql = new StringBuffer();
        while (varMatcher.find()) {
            String varName = varMatcher.group(1).trim();
            Object value = context.getOrDefault(varName, "");
            varMatcher.appendReplacement(parsedSql, Matcher.quoteReplacement(String.valueOf(value)));
        }
        varMatcher.appendTail(parsedSql);
        return parsedSql.toString();
    }

    default R processSql(String sql) {
        return null;
    }
}
